package com.xjl.example.commonUnsafe;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 2019年12月25日10:51:12
 * StringBuilder是线程不安全的
 */
@Slf4j
public class HashMapExample {

    private final static int totalCount = 5000;
    private final static int threadCount =200;

    static Map<Integer,Integer> hashMap = new HashMap<>();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);
        final CountDownLatch count = new CountDownLatch(totalCount);
        for (int i = 0; i < totalCount; i++) {
          final  int finalI = i;
            service.execute(() -> {
                try {
                    semaphore.acquire();
                    add(finalI);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.countDown();
            });
        }
        count.await();
        service.shutdown();
        log.info("size{}",hashMap.size());

    }

    private static void add(int i) {
        hashMap.put(i,i);

    }


}
